package tq.com.tqstudent.ui.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.lib.common.base.BaseFragment;
import com.lib.common.utils.LogUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.Subscribe;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import tq.com.tqstudent.App;
import tq.com.tqstudent.Constants;
import tq.com.tqstudent.R;
import tq.com.tqstudent.adapter.common.CommonAdapter;
import tq.com.tqstudent.adapter.common.MultiItemTypeAdapter;
import tq.com.tqstudent.adapter.common.ViewHolder;
import tq.com.tqstudent.bean.AuthorBean;
import tq.com.tqstudent.bean.BaseBean;
import tq.com.tqstudent.bean.UserInfo;
import tq.com.tqstudent.bean.event.ChatEvent;
import tq.com.tqstudent.net.ok.DialogCallback;
import tq.com.tqstudent.net.ok.StringCallback;
import tq.com.tqstudent.ui.activity.classes.ChatActivity;
import tq.com.tqstudent.utils.VarietyUtil;

/**
 * 私信
 *
 * @Author rames
 * @date 2019/8/16 22:32
 */
public class MsgFragment extends BaseFragment {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.empty_layout)
    LinearLayout emptyLayout;
    private CommonAdapter adapter;
    private boolean isLoaded = false;
    private int pageNO = 1;
    private static int WHILE_GET_UNREAD_COUNT = 5*1000; //5秒钟轮询一次是否有私信的小红点

    @Override
    protected int setView() {
        return R.layout.fragment_recode;
    }

    @Override
    protected void init(View view) {
        if (isVisible() && isLoaded) {
            return;
        }
        isLoaded = false;

        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter = new CommonAdapter<AuthorBean>(mActivity, R.layout.item_activity_msg, new ArrayList()) {
            @Override
            protected void convert(ViewHolder holder, AuthorBean bean, int position) {
                holder.setVisible(R.id.point_iv, bean.unread_count > 0);
                if (bean.last_msg != null) {
                    holder.setText(R.id.msg_tv, VarietyUtil.getContentByType(bean.last_msg.content_type, bean.last_msg.content));
                    holder.setText(R.id.time_tv, bean.last_msg.time);
                }

                if (bean.teacher != null) {
                    holder.setText(R.id.name_tv, bean.teacher.name + "(" + VarietyUtil.getSubjectName(bean.teacher.subject) + ")");
                    Glide.with(mActivity).load(VarietyUtil.getHeadImgUri(bean.teacher.pic)).apply(VarietyUtil.getGlideHeadOptions()).into((ImageView) holder.getView(R.id.head_iv));
                }
            }
        };

        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                AuthorBean bean = (AuthorBean) adapter.getDatas().get(position);
                setReadPoint(bean.teacher.id, false);
                ChatActivity.show(mActivity, false, bean.teacher.name, bean.teacher.id, 0, position);
            }
        });
        recyclerView.setAdapter(adapter);

        refreshLayout.setOnRefreshListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageNO++;
                getData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNO = 1;
                getData();
            }
        });

//        changeStatus();
    }

    private void changeStatus() {
        if (!UserInfo.isLogin()) {
            if(adapter.getDatas().size() < 1) {
                emptyLayout.setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.GONE);
            }
            VarietyUtil.setRefreshEnable(refreshLayout, false);
        }
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
//        changeStatus();
//        if(null == adapter || adapter.getDatas().size() < 1) {
//            if(UserInfo.isLogin()) {
//                refreshLayout.autoRefresh();
//            }
//        }
    }

    private void refresh() {
//        if (null == adapter || adapter.getDatas().size() < 1) {
            if (UserInfo.isLogin()) {
                refreshLayout.autoRefresh();
            }
//        }
        changeStatus();
    }

    @Subscribe
    public void onRefreshEvent(ChatEvent event) {
        refresh();
    }

    @Override
    public void onResume() {
        super.onResume();
        refresh();
    }

    private void getData() {
        String uri = "api/clz/myteacher";
        OkGo.<BaseBean<List<AuthorBean>>>get(App.getHttpUrl(uri))
                .tag(this)
                .execute(new DialogCallback<List<AuthorBean>>(mActivity, false) {
                    @Override
                    public void handleSuccess(List<AuthorBean> data) {
                        // 这是加载更多
                        if (refreshLayout.getState() == RefreshState.Loading) {
                            adapter.addData(data);
                            refreshLayout.finishLoadMore();
                            if (data.size() < Constants.PAGE_SIZE) {
                                refreshLayout.setEnableLoadMore(false);
                            }

                            // 这是下拉刷新
                        } else {
                            adapter.getDatas().clear();
                            adapter.setData(data);
                            refreshLayout.setEnableLoadMore(true);
                            refreshLayout.finishRefresh();
                        }

                        unReadHandler.sendEmptyMessageDelayed(0, WHILE_GET_UNREAD_COUNT);
                        emptyLayout.setVisibility(recyclerView.getAdapter().getItemCount() > 0 ? View.GONE : View.VISIBLE);
                    }

                    @Override
                    public void handleFail(BaseBean body) {
                        super.handleFail(body);
                        refreshLayout.finishLoadMore();
                        refreshLayout.finishRefresh();
                    }
                });
    }

    /**
     * 设置小红点的已读
     *
     * @param targetID
     * @param isGroup  目标类型： 0 表示是目标是普通用户， 1 表示目标是群组
     */
    private void setReadPoint(int targetID, boolean isGroup) {
        String uri = "api/im/setread";
        String json = "{\"target_id\"" + ":" + targetID + ",\"score\"" + ":" + (isGroup ? 1 : 0) + "}";
        OkGo.<String>post(App.getHttpUrl(uri))
                .tag(this)
                .upJson(json)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }

                    @Override
                    public void onError(Response<String> response) {

                    }
                });
    }

    private int index = 0;
    private Handler unReadHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            index++;
            LogUtil.e(" 请求index: "+index);
//            unReadHandler.sendEmptyMessageDelayed(0, WHILE_GET_UNREAD_COUNT);
            getData();
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();

        if(unReadHandler != null){
            unReadHandler.removeMessages(0);
            unReadHandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    public void onPause() {
        super.onPause();

        if(unReadHandler != null){
            unReadHandler.removeMessages(0);
            unReadHandler.removeCallbacksAndMessages(null);
        }
    }
}
